let app = getApp()
let socketOpen = false
let socketMsgQueue = []
import datetime from '../../../yb_shopv2/utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    vueId:0,
    wordsFlag: !1,
    wordsMsg: "",
    params: {
        id:'',
        toid: "",
        staff_chatid:'',
        user_openid: "",
        page: 1,
        target: 1,
        send_type: "1",
        status: "2",
        imgUrl: "",
        name: "",
        from: ""
    },
    val: "",
    navArr: [ {
        url: "../../static/image/saveUser.png",
        txt: "保存联系人"
    }, {
        url: "../../static/image/joinFollow.png",
        txt: "加入跟进"
    }, {
        url: "../../static/image/customerData.png",
        txt: "客户资料"
    } ],
    chatArr: [],
    scrolltop: "",
    scrollHeight: "",
    bottom: 0,
    nodata: !1,
    nav: {
        show: !0
    },
    uservatar:''
  },
  user_busStaff:function(){
    var that=this
    wx.request({
        url: app.globalData.siteroot,
        data: {
            do:'Member_staffInfo',
            staff_id:wx.getStorageSync('staff_bind_id')
        },
        success: function(res) {
            that.setData({
                staff_chatid:res.data.info.chatid
            })
            wx.request({
              url: app.globalData.siteroot,
              data: {
                  do:'Buschat_getMessage',
                  toid:that.data.options.id,
                  user_openid:that.data.options.user_openid,
                  page: 1,
                  target: 1,
                  send_type: 1,
                  status: 2,
                  imgUrl:decodeURIComponent(that.data.options.imgUrl),
                  name:that.data.options.name,
                  cus_id:that.data.options.cus_id,
                  md5:that.data.options.md5,
                  phone:that.data.options.phone,
                  is_intention:that.data.options.is_intention,
                  staff_id:wx.getStorageSync('staff_bind_id'),
                  staff_chatid:that.data.staff_chatid
              },
              success: function(res) {
                     that.setData({
                      chatArr:res.data.data,
                      scrollTop:100000
                    })
              }
            })
            wx.request({
              url: app.globalData.siteroot,
              data: {
                  do:'Chat_msgStatus',
                  toid:that.data.options.id,
                  user_openid:that.data.options.user_openid,
                  page: 1,
                  target: 1,
                  send_type: 1,
                  status: 2,
                  imgUrl:decodeURIComponent(that.data.options.imgUrl),
                  name:that.data.options.name,
                  cus_id:that.data.options.cus_id,
                  md5:that.data.options.md5,
                  phone:that.data.options.phone,
                  is_intention:that.data.options.is_intention,
                  staff_id:wx.getStorageSync('staff_bind_id'),
                  staff_chatid:that.data.staff_chatid
              },
              success: function(res) {
              
              }
            })
          

        }
      })
  },
  uploadimg:function(){
    var that = this;
    wx.chooseImage({
      success: function(t) {
        var a = t.tempFilePaths;
        that.upload_file(t.tempFilePaths[0])
      }
    })
  },
  upload_file: function (filePath) {
    var that = this;
    wx.uploadFile({
    url:app.globalData.siteroot+'&do=Index_uploadFile',
    filePath: filePath,
    name: 'file_upload',
    header: {
    'content-type': 'multipart/form-data'
    }, 
    formData: {
    'do':'Index_uploadFile',
    },
    success: function (res) {
      var data=JSON.parse(res.data)
      if(data.code==200){
        var c = that.formatDateTime();
        that.setData({
          val:data.info.url
        })
        that.sendimg();
      }
    },
    fail: function (res) {}
    })
  },
  sendimg:function(e){
    var that=this
    var send_time = this.formatDateTime();
    var msg = JSON.stringify({
      'data': 'ping'
     })
     wx.sendSocketMessage({
      data: msg,
      success: function (res) {
        console.log(res)
        console.log('发送心跳')
      },
      fail: function (res) { 
        console.log(res)
        connect(that.data.options.user_openid)
        console.log('心跳发送失败')}
    })
    var t = JSON.stringify({
        type:"say",
        uid:that.data.staff_chatid,
        toid:that.data.options.user_openid,
        image:1,
        msg:that.data.val
      })
      wx.sendSocketMessage({
        data: t,
        success: function(e) {
            console.log(e);
            console.log("发送成功");
        },
        fail: function(e) {
            console.log(e);
            console.log("发送失败");
        }
     });
     wx.request({
      url: app.globalData.siteroot,
      data: {
          do:'Buschat_getMessage',
          toid:that.data.options.id,
          user_openid:that.data.options.user_openid,
          page: 1,
          target: 1,
          send_type: 1,
          status: 2,
          imgUrl:decodeURIComponent(that.data.options.imgUrl),
          name:that.data.options.name,
          cus_id:that.data.options.cus_id,
          md5:that.data.options.md5,
          phone:that.data.options.phone,
          is_intention:that.data.options.is_intention,
          staff_id:wx.getStorageSync('staff_bind_id'),
          staff_chatid:that.data.staff_chatid
      },
      success: function(res) {
      }
    })
     wx.request({
      url: app.globalData.siteroot,
      data: {
        do:'Buschat_putMessage',
        toid:wx.getStorageSync('user_id'),
        staff_chatid:that.data.staff_chatid,
        user_openid:that.data.options.user_openid,
        staff_id:wx.getStorageSync('staff_bind_id'),
        send_type:2,
        status:2,
        target:1,
        content:that.data.val,
        imgUrl:decodeURIComponent(that.data.options.imgUrl),
        name: that.data.options.name,
        cus_id: that.data.options.cus_id,
        md5:that.data.options.md5,
        phone: that.data.options.phone,
        is_intention:that.data.options.is_intention,
      },
      success: function(res) {
        var service={
          create_time:send_time,
          content:that.data.val,
          staff_avatar:wx.getStorageSync('staff_user').avatar,
          user_avatar:wx.getStorageSync('staff_user').avatar,
          target: 1,
          status: 2,
          send_type: 2
       }
       var newchat= that.data.chatArr
       newchat.push(service);
       that.setData({
         chatArr:newchat,
         scrollTop:that.data.scrollTop+100
       })
        that.setData({
          val:''
        })
      }
    })
    
  },
  conatct:function(e){
          const id = e.currentTarget.dataset.id;
          if(id==0)
          {
            var user_name=this.data.options.name;
            var phone=this.data.options.phone;
            if(user_name==''){
              return false
            }
            wx.addPhoneContact({
              firstName:user_name,
              mobilePhoneNumber:phone,
              success: function() {
                wx.showToast({
                  title:'保存成功',
                  icon:'success'
                })
                console.log("保存成功");
              },
              fail: function() {
                console.log("取消保存");
              }
            })
          }else if(id==1){
            var t=this.data.options
            var a = "../staff_customer/customerInfo/index?imgUrl=" + t.imgUrl + "&name=" + t.name + "&from=" + t.from + "&cus_id=" + t.cus_id + "&user_openid=" + t.user_openid + "&md5=" + t.md5 + "&phone=" + t.phone + "&user_id=" + t.id;
            wx.navigateTo({
             url:a
           })
          }else if(id==2){
            var t=this.data.options
            var a = "../staff_customer/customerInfo/editInfo?imgUrl=" +encodeURIComponent(t.imgUrl)+ "&name=" + t.name + "&from=" + t.from + "&cus_id=" + t.cus_id + "&user_openid=" + t.user_openid + "&md5=" + t.md5 + "&phone=" + t.phone + "&user_id=" + t.id;
            wx.navigateTo({
             url:a
           })
          }
       
  },
  chooseword:function(e){
    this.setData({
      wordsFlag:false,
      vueId:0,
      val:e.detail
    })
  },
  changyong:function(){
    this.setData({
      wordsFlag:true,
      vueId:1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    this.setData({
      options:options
    })
    that.wssInit(options.user_openid)
    that.user_busStaff();
    this.setData({
        globalColor:app.globalData.globalColor,
        options:options
      })
      Promise.all([
        that.getCode(wx.getStorageSync('userinfo').user_headimg)
       ]).then(res=>{
        that.setData({ 
          user_avatar:res[0].tempFilePath
        })
       })
       setInterval(() => {
        that.user_busStaff();
      }, 3000)

  },
  getCode(img){
    return new Promise((resolve,reject)=>{
      wx.downloadFile({
        url: img,
        success: (res) => {
          resolve(res)
        }
      })
    })
  },
  talk:function(e){
    this.setData({
      val:e.detail.value
    })
  },
  send:function(e){
    var that=this
    var send_time = this.formatDateTime();
    var t = JSON.stringify({
        type:"say",
        uid:that.data.staff_chatid,
        toid:that.data.options.user_openid,
        image:0,
        msg:that.data.val
      })
      wx.sendSocketMessage({
        data: t,
        success: function(e) {
            console.log(e);
            console.log("发送成功");
        },
        fail: function(e) {
            console.log(e);
            console.log("发送失败");
        }
     });
     wx.request({
      url: app.globalData.siteroot,
      data: {
        do:'Buschat_putMessage',
        toid:wx.getStorageSync('user_id'),
        staff_chatid:that.data.staff_chatid,
        user_openid:that.data.options.user_openid,
        staff_id:wx.getStorageSync('staff_bind_id'),
        send_type:1,
        status:2,
        target:1,
        content:that.data.val,
        imgUrl:decodeURIComponent(that.data.options.imgUrl),
        name: that.data.options.name,
        cus_id: that.data.options.cus_id,
        md5:that.data.options.md5,
        phone: that.data.options.phone,
        is_intention:that.data.options.is_intention,
      },
      success: function(res) {
        var service={
          create_time:send_time,
          content:that.data.val,
          staff_avatar:wx.getStorageSync('staff_user').avatar,
          user_avatar:wx.getStorageSync('staff_user').avatar,
          target: 1,
          status: 2,
          send_type: 1
       }
       var newchat= that.data.chatArr
       newchat.push(service);
       that.setData({
         chatArr:newchat,
         scrollTop:that.data.scrollTop+100
       })
        that.setData({
          val:''
        })
      }
    })
    
  },
  formatDateTime: function() {
    var t = new Date(), e = t.getFullYear(), a = t.getMonth() + 1;
    a = a < 10 ? "0" + a : a;
    var o = t.getDate();
    o = o < 10 ? "0" + o : o;
    var s = t.getHours();
    s = s < 10 ? "0" + s : s;
    var n = t.getMinutes();
    n = n < 10 ? "0" + n : n;
    var i = t.getSeconds();
    return i = i < 10 ? "0" + i : i, e + "-" + a + "-" + o + " " + s + ":" + n + ":" + i;
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that=this
    setInterval(() => {
      var msg = JSON.stringify({
        'data': 'ping'
    })
    wx.sendSocketMessage({
      data: msg,
      success: function (res) {
        console.log(res)
        console.log('发送心跳')
      },
      fail: function (res) { 
        console.log(res)
        connect(that.data.options.user_openid)
        console.log('心跳发送失败')}
    })
   }, 3000)
  },
  wssInit (user_openid) {
    var that = this;
      this.connectWss(user_openid);
      // 链接失败显示
      wx.onSocketError(function (res) {
        console.log('WebSocket连接打开失败，请检查！', res);
        console.log('staff_chatid', wx.getStorageSync('staff_chatid'));
        console.log('user_openid', user_openid);
        that.setData({
          isOpen: false,
          statusMsg: '已断开'
        });
      });
      // 监听连接成功
      wx.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开0！')
        wx.sendSocketMessage({
          data: JSON.stringify({
            type:"bind",
            uid:wx.getStorageSync('staff_chatid'),
            toid:user_openid,
            msg:''
          }),
          success: res => {
            console.log(res+'发送成功')
          },
          fail: err=> {
            console.log(err+'失败')
          }
        })
        that.setData({
          isOpen: true,
          statusMsg: '已连接'
        });
        wx.onSocketMessage(function (res) {
          var res_data = JSON.parse(res.data);
          console.log(res_data)
          console.log('接收到0：'+res_data.type)
          switch (console.log(res_data), res_data.type) {
            case "init":
              console.log('bind')
              break;

            case "ping":
              console.log('ping')
              break;

            case "notice":
              console.log('notice')
              break;

            default:
              console.log('文字')
          }
          if(res_data.type=='say'||res_data.type=='image'){
            console.log('接收到：'+res_data.type)
            var nowtime= new Date().getTime();
            var s=datetime.formatDate(nowtime)
            var send_type=1
            if(res_data.type=='image'){
                send_type=2
            }
            var msg={
              staff_chatid:wx.getStorageSync('staff_chatid'),
              user_openid:that.data.options.user_openid,
              content:res_data.msg,
              user_avatar:decodeURIComponent(that.data.options.imgUrl),
              create_time:s,
              target:2,
              send_type:send_type
            }
            that.data.chatArr.push(msg)
            that.setData({
              isUser: true,
              chatArr: that.data.chatArr,
              scrollTop:that.data.scrollTop+100
            })
          
          }
        
        
        });
      
      })
    },

  connectWss: function (user_openid) {
      this.setData({
        statusMsg: '连接中。。。'
      });
      console.log('链接id:'+user_openid)
      connect(user_openid);
    },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
       
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      wx.closeSocket();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
function connect(user_openid) {
  console.log('发送id:'+user_openid)
  wx.connectSocket({
    url:app.globalData.vwss,
    success: function (res) {
      wx.sendSocketMessage({
        data: JSON.stringify({
          type:"bind",
          uid: wx.getStorageSync('staff_chatid'),
          toid:user_openid,
          msg:''
        }),
        success: res => {
          console.log(res+'发送成功')
        },
        fail: err=> {
          console.log(err+'失败')
        }
      });
     
    }
  });
}